package com.raulraja.util.deployment;

import org.apache.log4j.Logger;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.context.support.ServletContextResource;

import java.net.UnknownHostException;
import java.net.InetAddress;

/**
 * A service that provides a resource based on the host name
 */
public class CompositeStringResourceProvider {

    private final static Logger log = Logger.getLogger(CompositeStringResourceProvider.class);

    private final static String HOSTNAME_PLACEHOLDER = "_HOST_NAME_";

	/**
	 * This method is invoked by the container at startup
	 * @param servletContextProvider a servlet context provider
	 * @param baseResource the base resource
	 * @return the resource assigned to the current running server
	 * @throws UnknownHostException if the host is unknown
	 */
    public static Resource getReplacedResource(ServletContextProvider servletContextProvider, String baseResource) throws UnknownHostException {
        InetAddress localhost = InetAddress.getLocalHost();
        baseResource = baseResource.replaceAll(HOSTNAME_PLACEHOLDER, localhost.getHostName());
        Resource resource = null;
        if (servletContextProvider.getServletContext() != null) {
            resource = new ServletContextResource(servletContextProvider.getServletContext(), baseResource);
            if (resource.exists()) {
                log.debug("Loading override for common properties: " + resource.getFilename());
            }
        } else {
            resource = new ClassPathResource(baseResource);
        }

        return resource;
    }

}
